var util = require('../../utils/util.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
var code = '';

const date = new Date();
const years = [];
const months = [];
const days = [];
const hours = [];
const minutes = [];
//获取年
for (let i = 2020; i <= date.getFullYear() + 5; i++) {
  years.push("" + i);
}
//获取月份
for (let i = 1; i <= 12; i++) {
  if (i < 10) {
    i = "0" + i;
  }
  months.push("" + i);
}
//获取日期
for (let i = 1; i <= 31; i++) {
  if (i < 10) {
    i = "0" + i;
  }
  days.push("" + i);
}
//获取小时
for (let i = 0; i < 24; i++) {
  if (i < 10) {
    i = "0" + i;
  }
  hours.push("" + i);
}
//获取分钟
for (let i = 0; i < 60; i++) {
  if (i < 10) {
    i = "0" + i;
  }
  minutes.push("" + i);
}

let dogcode = ''; //编码
Page({
  data: {
    statusBarHeight: 0, //胶囊按钮高度
    mtop0: 0, //弹窗高度1
    mtop1: 0, //弹窗高度2
    bl0: true, //黑色背景
    bl1: true, //上传封面
    bl2: true, //赏金面议
    bl3: false, //提示
    bl4: true, //发布成功
    bl5: true, //扫码名片
    sel_index0: 0, //输入框
    errmsg: '', //表单检索提示
    fcolor: '', //宠物颜色
    fpz: '', //宠物品种
    fdes: '', //描述
    ftel: '', //手机号
    imgewm: '', //群二维码
    time: '', //走失时间
    multiArray: [years, months, days, hours, minutes],
    multiIndex: [0, 9, 16, 10, 17],
    choose_year: '',

    imgList: [], //封面

    longitude: '',
    latitude: '',
    address: '点击地图可选择位置',
    markers: [],
    painting: {},
    saveImage: ''
  },
  onLoad: function (options) {
    wx.hideShareMenu()
    qqmapsdk = new QQMapWX({
      key: getApp().globalData.mapkey
    });
    var dayTime = util.formatTime(new Date());
    var newDate = /\d{4}\/\d{1,2}\/\d{1,2} \d{1,2}:\d{1,2}/g.exec(dayTime)
    console.log(newDate[0]);

    let slet = this;
    let longitude = getApp().globalData.longitude;
    let latitude = getApp().globalData.latitude;
    console.log(longitude);
    console.log(latitude);

    let statusBarHeight = getApp().globalData.statusBarHeight;
    console.log('statusBarHeight:', statusBarHeight);
    console.log('windowHeigh:', wx.getSystemInfoSync().windowHeight);
    let screen = wx.getSystemInfoSync().windowWidth / 750;
    console.log('screenWidth:', screen);
    let mtop = wx.getSystemInfoSync().windowHeight - 620 * screen - (74 + statusBarHeight) * screen;
    mtop = mtop / 2;
    let mtop0 = mtop + (74 + statusBarHeight) * screen;
    console.log('mtop0:', mtop0);

    mtop = wx.getSystemInfoSync().windowHeight - 1060 * screen - (74 + statusBarHeight) * screen;
    mtop = mtop / 2;
    let mtop1 = mtop + (74 + statusBarHeight) * screen;
    console.log('mtop1:', mtop1);

    //逆向解析地址
    // qqmapsdk.reverseGeocoder({
    //   location: {
    //     latitude: latitude,
    //     longitude: longitude
    //   },
    //   success: function (res) {
    //     let province = res.result.ad_info.province
    //     let city = res.result.ad_info.city
    //     console.log(res.result);
    //     slet.setData({
    //       address:res.result.address
    //     })
    //   },
    //   fail: function (res) { console.log(res); },
    //   complete: function (res) { }
    // });
    let time = newDate[0];
    time = time.replace(/\//g, '-');
    let painting = {
      width: 680,
      height: 960,
      clear: true,
      views: [{
        type: 'image',
        url: '/img/icon_11.png',
        top: 0,
        left: 0,
        width: 680,
        height: 960,
      }, {
        type: 'image',
        url: getApp().globalData.xcxinfodata.imgewm,
        top: 350,
        left: 203,
        width: 274,
        height: 274
      }]
    }
    slet.setData({
      mtop0: mtop0,
      mtop1: mtop1,
      statusBarHeight: getApp().globalData.statusBarHeight,
      time: time,
      choose_year: slet.data.multiArray[0][0],
      longitude: longitude,
      latitude: latitude,
      imgewm: getApp().globalData.xcxinfodata.imgewm,
      painting
    })
  },
  onShow: function () {
    wx.login({ //login流程
      success: function (res) { //登录成功
        if (res.code) {
          code = res.code;
        }
      }
    })
  },
  selInput(e) //输入框得到焦点
  {
    let slet = this;
    let index = e.currentTarget.dataset.index;
    slet.setData({
      sel_index0: index
    })
  },
  blurInput(e) //输入框失去焦点
  {
    let slet = this;
    slet.setData({
      sel_index0: 0
    })
  },
  getPhoneNumber(e) { //授权手机号
    let slet = this;
    let msg = e.detail.errMsg;
    let iv = e.detail.iv;
    let encryptedData = e.detail.encryptedData;
    if (msg == "getPhoneNumber:ok") {
      wx.request({
        url: getApp().data.apiUrl + '/GetDecryptPhone.ashx',
        data: {
          code: code,
          encryptedData: encodeURIComponent(encryptedData),
          iv: iv
        },
        method: 'GET',
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          console.log(res.data);
          if (res.data.status == 1) //成功
          {
            slet.setData({
              ftel: res.data.tel
            })
            wx.login({ //login流程
              success: function (res) { //登录成功
                if (res.code) {
                  code = res.code;
                }
              }
            })
          } else {
            wx.showToast({
              title: '获取失败，请手动输入',
              icon: 'none',
              duration: 1000
            })
          }
        }
      })
    }
  },
  uploadImg(e) //上传封面
  {
    let slet = this;
    let mediaType = ['image']
    if (this.data.imgList.length > 0) {
      mediaType = ['image', 'video']
    }
    wx.chooseMedia({
      count: 1,
      mediaType: mediaType,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log(res);
        wx.uploadFile({
          url: getApp().data.apiUrl + '/UploadImg.ashx',
          filePath: res.tempFiles[0].tempFilePath,
          name: 'fileimages',
          formData: {},
          success: function (res) {
            var resData = JSON.parse(res.data);
            console.log('ImagesUpload:', resData);
            if (resData.status == 1) {
              var imgdata = {
                imgname: resData.imagename,
                imageurl: resData.imageurl,
                type: resData.type
              };
              let imgList = slet.data.imgList.concat(imgdata);
              console.log('imgList:', imgList);
              if (imgList.length <= 3) {
                slet.setData({
                  imgList: imgList,
                  bl1: false
                })
              } else {
                wx.showModal({
                  title: '温馨提示',
                  showCancel: false,
                  content: '最多可上传三张图片'
                })
              }
            } else {
              wx.showToast({
                title: resData.msg,
                icon: 'none',
                duration: 1000
              })
            }
          }
        })

      }
    })
  },
  bindColor(e) { //输入颜色
    let slet = this;
    slet.setData({
      fcolor: e.detail.value
    })
  },
  bindPz(e) { //输入品种
    let slet = this;
    slet.setData({
      fpz: e.detail.value
    })
  },
  bindDes(e) { //输入描述
    let slet = this;
    slet.setData({
      fdes: e.detail.value
    })
  },
  //移动选点
  moveToLocation: function () {
    var slet = this;
    wx.chooseLocation({
      success: function (res) {
        console.log(res);
        let mobileLocation = {
          longitude: res.longitude,
          latitude: res.latitude,
          address: res.address,
          name: res.name
        };
        let markers = [{
          latitude: res.latitude,
          longitude: res.longitude,
          iconPath: '/img/icon_231.png'
        }]
        slet.setData({
          address: mobileLocation.address,
          longitude: mobileLocation.longitude,
          latitude: mobileLocation.latitude,
          markers: markers
        });
      },
      fail: function (err) {
        wx.getSetting({
          success: (res) => {
            if (!res.authSetting['scope.userLocation']) {
              wx.showModal({
                content: '检测到您没打开定位权限，是否去设置打开？',
                confirmText: "确认",
                cancelText: "取消",
                success: function (res) {
                  if (res.confirm) {
                    wx.openSetting({ //二次获取授权
                      success: (res) => {
                        slet.getLocation(); //获取位置信息
                      }
                    })
                  } else {}
                }
              });
            }
          }
        })
      }
    });
  },
  bindTel(e) { //输入手机号
    let slet = this;
    slet.setData({
      ftel: e.detail.value
    })
  },
  bindSava(e) //立即发布
  {
    let slet = this;
    let imgList = slet.data.imgList; //封面
    let fcolor = slet.data.fcolor;
    let fpz = slet.data.fpz;
    let time = slet.data.time;
    let fdes = slet.data.fdes;
    let ftel = slet.data.ftel;
    let longitude = slet.data.longitude;
    let latitude = slet.data.latitude;
    let address = slet.data.address;
    let bl3 = true;
    let errmsg = ''; //提示
    if (imgList.length == 0) {
      errmsg = '还未上传封面~'
    } else if (fcolor == '') {
      errmsg = '还未填写颜色~'
    } else if (fpz == '') {
      errmsg = '还未填写品种信息~'
    } else if (longitude == '' || latitude == '' || address == '点击地图可选择位置') {
      errmsg = '还未选择发现地点~'
    } else if (ftel == '') {
      errmsg = '请输入手机号方便收取线索~'
    } else {
      bl3 = false;
    }
    slet.setData({
      bl3: bl3,
      errmsg: errmsg
    })
    let img = '';
    let img1 = '';
    let img2 = '';
    if (imgList.length > 0) {
      img = imgList[0].imgname;
    }
    if (imgList.length > 1) {
      img1 = imgList[1].imgname;
    }
    if (imgList.length > 2) {
      img2 = imgList[2].imgname;
    }
    if (bl3 == false) //信息效验通过
    {
      let tmplIds2 = getApp().globalData.xcxinfodata.tmplIds3;
      if (tmplIds2.length > 10) {
        let tmplIds = '[' + tmplIds2 + ']' //订阅消息ID
        tmplIds = tmplIds.replace(/@/g, '"');
        tmplIds = JSON.parse(tmplIds);
        wx.requestSubscribeMessage({
          tmplIds: tmplIds,
          success(res) {
            console.log(res);
            wx.request({
              url: getApp().data.apiUrl + '/AddDog02.ashx',
              data: {
                type: 1, //寻狗启事
                token: wx.getStorageSync('LoginSessionKey'),
                img: img,
                img1: img1,
                img2: img2,
                colour: encodeURI(fcolor),
                pz: encodeURI(fpz),
                time: time,
                address: encodeURI(address),
                long: longitude,
                lat: latitude,
                tel: ftel,
                des: encodeURI(fdes),
              },
              method: 'POST',
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
                console.log(resdata);
                if (resdata.state == 1) {
                  dogcode = resdata.code;
                  slet.setData({
                    bl0: false,
                    bl4: false,
                  })
                } else {
                  wx.showToast({
                    title: resdata.msg,
                    icon: 'none',
                    duration: 1000
                  })
                }
              }
            })
          }
        });
      } else {
        wx.request({
          url: getApp().data.apiUrl + '/AddDog02.ashx',
          data: {
            type: 1, //寻狗启事
            token: wx.getStorageSync('LoginSessionKey'),
            img: img,
            img1: img1,
            img2: img2,
            colour: encodeURI(fcolor),
            pz: encodeURI(fpz),
            time: time,
            address: encodeURI(address),
            long: longitude,
            lat: latitude,
            tel: ftel,
            des: encodeURI(fdes),
          },
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            var resdata = JSON.parse(decodeURIComponent(JSON.stringify(res.data)));
            console.log(resdata);
            if (resdata.state == 1) {
              dogcode = resdata.code;
              slet.setData({
                bl0: false,
                bl4: false,
              })
            } else {
              wx.showToast({
                title: resdata.msg,
                icon: 'none',
                duration: 1000
              })
            }
          }
        })
      }
    }
  },
  OpenEwm(e) //同城寻宠群
  {
    let slet = this;
    slet.setData({
      bl5: false
    })
  },
  CreateHb(e) //生成海报
  {
    wx.navigateTo({
      url: '../qs/fx?code=' + dogcode,
    })
  },
  getLocation() //获取位置信息
  {
    let slet = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        const latitude = res.latitude
        const longitude = res.longitude
        const speed = res.speed
        const address = res.address
        getApp().globalData.longitude = longitude;
        getApp().globalData.latitude = latitude;
        slet.setData({
          address: address,
          longitude: longitude,
          latitude: latitude,
        })
      },
      fail(res) {
        console.log(res);
      }
    })
  },
  selPicker(e) //时间选择器点击触发
  {

    let slet = this;
    let date = new Date();
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()

    let index0 = 1;
    let index1 = 0;
    let index2 = 0;
    let index3 = 0;
    let index4 = 0;

    for (var i = 0; i < years.length; i++) {
      if (years[i] == year) {
        index0 = i;
      }
    }
    for (var i = 0; i < months.length; i++) {
      if (months[i] == month) {
        index1 = i;
      }
    }
    for (var i = 0; i < days.length; i++) {
      if (days[i] == day) {
        index2 = i;
      }
    }
    for (var i = 0; i < hours.length; i++) {
      if (hours[i] == hour) {
        index3 = i;
      }
    }
    for (var i = 0; i < minutes.length; i++) {
      if (minutes[i] == minute) {
        index4 = i;
      }
    }

    slet.setData({
      multiIndex: [
        index0,
        index1,
        index2,
        index3,
        index4
      ]
    })
  },
  //获取时间日期
  bindMultiPickerChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      multiIndex: e.detail.value
    })
    const index = this.data.multiIndex;
    const year = this.data.multiArray[0][index[0]];
    const month = this.data.multiArray[1][index[1]];
    const day = this.data.multiArray[2][index[2]];
    const hour = this.data.multiArray[3][index[3]];
    const minute = this.data.multiArray[4][index[4]];
    // console.log(`${year}-${month}-${day}-${hour}-${minute}`);
    this.setData({
      time: year + '-' + month + '-' + day + ' ' + hour + ':' + minute
    })
    // console.log(this.data.time);
  },
  //监听picker的滚动事件
  bindMultiPickerColumnChange: function (e) {
    let slet = this;
    //获取年份
    if (e.detail.column == 0) {
      let choose_year = slet.data.multiArray[e.detail.column][e.detail.value];
      slet.setData({
        choose_year
      })
    }
    if (e.detail.column == 1) {
      let num = parseInt(slet.data.multiArray[e.detail.column][e.detail.value]);
      let temp = [];
      if (num == 1 || num == 3 || num == 5 || num == 7 || num == 8 || num == 10 || num == 12) { //判断31天的月份
        for (let i = 1; i <= 31; i++) {
          if (i < 10) {
            i = "0" + i;
          }
          temp.push("" + i);
        }
        slet.setData({
          ['multiArray[2]']: temp
        });
      } else if (num == 4 || num == 6 || num == 9 || num == 11) { //判断30天的月份
        for (let i = 1; i <= 30; i++) {
          if (i < 10) {
            i = "0" + i;
          }
          temp.push("" + i);
        }
        slet.setData({
          ['multiArray[2]']: temp
        });
      } else if (num == 2) { //判断2月份天数
        let year = parseInt(slet.data.choose_year);
        console.log(year);
        if (((year % 400 == 0) || (year % 100 != 0)) && (year % 4 == 0)) {
          for (let i = 1; i <= 29; i++) {
            if (i < 10) {
              i = "0" + i;
            }
            temp.push("" + i);
          }
          slet.setData({
            ['multiArray[2]']: temp
          });
        } else {
          for (let i = 1; i <= 28; i++) {
            if (i < 10) {
              i = "0" + i;
            }
            temp.push("" + i);
          }
          slet.setData({
            ['multiArray[2]']: temp
          });
        }
      }
    }
    var data = {
      multiArray: slet.data.multiArray,
      multiIndex: slet.data.multiIndex
    };
    data.multiIndex[e.detail.column] = e.detail.value;
    slet.setData(data);
  },
  toClose(e) { //关闭
    let slet = this;
    slet.setData({
      bl4: true,
      bl5: true,
      bl0: true,
    })
  },
  toClose2(e) { //关闭二维码
    let slet = this;
    slet.setData({
      bl5: true
    })
  },
  toHome(e) //回首页
  {
    wx.reLaunch({
      url: '/pages/index',
    })
  },
  toBlack(e) //返回
  {
    wx.navigateBack({
      delta: 1
    })
  },
  saveImage() {
    wx.getSetting({
      success: ({
        authSetting
      }) => {
        if (authSetting.writePhotosAlbum) {
          this.saveImgT()
        } else {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: () => {
              this.saveImgT()
            },
            fail: () => {
              this.openSet()
            }
          })
        }
      }
    })
  },
  openSet() { // 打开设置页
    let _this = this
    wx.showModal({
      title: '提示',
      content: '请先允许保存到相册',
      success: function (res) {
        if (res.confirm) {
          wx.openSetting({
            withSubscriptions: true,
            success(res) {
              if (res.authSetting['scope.writePhotosAlbum']) {
                _this.saveImgT()
              }
            }
          });
        }
      }
    });
  },
  saveImgT() {
    wx.saveImageToPhotosAlbum({
      filePath: this.data.saveImage,
      success(res) {
        console.log('成功')
        wx.showToast({
          title: '图片保存成功',
          icon: 'none'
        })
      }
    })
  },
  eventGetImage(event) {
    wx.hideLoading()
    const {
      tempFilePath,
      errMsg
    } = event.detail
    if (errMsg === 'canvasdrawer:ok') {
      this.setData({
        saveImage: tempFilePath
      })
    }
  },
})